# coding=utf-8
import os
import configparser

import re
from flask import jsonify, json
from jproperties import Properties

from core.storeinfo import StoreInfo
from tools import globalvar
from tools.OperationError import OperationError
from tools.httpdoer import Request
import tools.convert as convert
from tools.properties import PropertiesUtils
from webapp.config import Config


class CpuCheck:
    def cpuCheck(self, cpu):

        try:
            # 在线模式
            print("cpuCheck cpu:" + str(cpu))
            request = Request(Config.ERP_URL + "api/pos/cpuCheck")
            print(Config.ERP_URL)
            request.method = "post"  # 调用 _set_method
            request.timeout = 10  # 调用 _set_timeout
            request.path_params = None
            request.query = {"CPU": cpu}
            r = request.send(json=False)

            if r is None:
                raise OperationError(-1, "服务端没有返回数据")
            else:
                # 处理数据
                self.setInfo(r)
        except Exception as e:
            # 在线报错是否抛出，由后期设计决定，暂时不抛出
            if type(e) != OperationError:
                raise e

        # 获取本地信息
        res = self.getInfo()
        if res == None or res == {}:
            raise OperationError(-1, "数据为空")

        return res

    def setInfo(self, response):

        print(response.text)

        if response.status_code != 200:
            raise OperationError(-1, response.text)

        if response.json == None:
            raise OperationError(-1, "服务器返回格式错误")  # print(type(res))

        res = convert.to_dict(response.json)
        if res["code"] == 0:
            message = res["message"]
            print(message)
            r_data = res.get("data", None)
            if r_data is None or len(r_data) <= 0:
                raise OperationError(-1, "没有激活店仓的记录")
            print(r_data)
            # 只取第一个
            arr = r_data[0]
            if arr is None:
                raise OperationError(-1, "没有激活店仓的记录")
            else:
                if arr["CHECK_STATUS"] == "N":
                    res["message"] = "待审核中，请联系IT管理员"
            # 保存店仓信息
            storeInfo = StoreInfo()
            storeInfo.saveStoreInfo(arr)

        # 保存返回值
        self.saveInfo(res)

    def saveInfo(self, res):
        if len(res) > 0:
            # 获取路径
            filename = Config.ROOT_PATH + os.sep + r"initconfig" + os.sep + "master.properties"
            PropertiesUtils().saveProperties(filename, Config.KEY_CUPCHECK, res)

    def getInfo(self):
        filename = Config.ROOT_PATH + os.sep + r"initconfig" + os.sep + "master.properties"
        print(filename)
        res = PropertiesUtils().getProperties(filename, Config.KEY_CUPCHECK)
        return res


if __name__ == "__main__":
    cpucheck = CpuCheck()
    json1 = cpucheck.cpuCheck("C17SNAT3GVC1")
    print(type(json1))
    print(json1)
